<template>
  <div class="device-channel-selector compact">
    <!-- 设备选择 -->
    <el-form-item :label="deviceLabel" class="selector-item compact-item">
      <el-select
        v-model="selectedDevice"
        :placeholder="devicePlaceholder"
        :clearable="clearable"
        :disabled="disabled"
        @change="handleDeviceChange"
        class="device-select compact-select"
        :loading="loading"
        size="small"
      >
        <!-- 添加请选择选项 -->
        <el-option
          label="请选择设备"
          value=""
        />
        <el-option
          v-for="device in deviceOptions"
          :key="device.value"
          :label="device.label"
          :value="device.value"
        />
      </el-select>
    </el-form-item>

    <!-- 通道选择 -->
    <el-form-item :label="channelLabel" class="selector-item compact-item">
      <el-select
        v-model="selectedChannel"
        :placeholder="channelPlaceholder"
        :clearable="clearable"
        :disabled="disabled || !selectedDevice"
        @change="handleChannelChange"
        class="channel-select compact-select"
        :loading="loading"
        size="small"
      >
        <!-- 添加请选择选项 -->
        <el-option
          label="请选择通道"
          value=""
        />
        <el-option
          v-for="channel in channelOptions"
          :key="channel.value"
          :label="channel.label"
          :value="channel.value"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script>
import { getDevicesAndChannels } from '@/api/project/monitor';

export default {
  name: 'DeviceChannelSelector',
  props: {
    // 双向绑定的设备编号
    value: {
      type: Object,
      default: () => ({
        deviceNo: '',
        channelNo: ''
      })
    },
    // 设备选择框标签
    deviceLabel: {
      type: String,
      default: '设备'
    },
    // 通道选择框标签
    channelLabel: {
      type: String,
      default: '通道'
    },
    // 设备选择框占位符
    devicePlaceholder: {
      type: String,
      default: '请选择设备'
    },
    // 通道选择框占位符
    channelPlaceholder: {
      type: String,
      default: '请选择通道'
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否自动选择第一个设备
    autoSelectFirstDevice: {
      type: Boolean,
      default: false  // 改为false，不自动选择
    },
    // 是否自动选择第一个通道
    autoSelectFirstChannel: {
      type: Boolean,
      default: false  // 改为false，不自动选择
    },
    // 是否在挂载时自动加载数据
    autoLoad: {
      type: Boolean,
      default: true
    },
    // 是否在首次加载后自动触发change事件
    autoEmitChange: {
      type: Boolean,
      default: false  // 改为false，不自动触发
    }
  },
  data() {
    return {
      selectedDevice: this.value.deviceNo || '',
      selectedChannel: this.value.channelNo || '',
      deviceOptions: [],
      channelOptions: [],
      allChannelsData: [], // 存储所有通道数据
      loading: false,
      isFirstLoad: true // 标记是否为首次加载
    };
  },
  watch: {
    // 监听外部传入的value变化
    value: {
      handler(newVal) {
        if (newVal.deviceNo !== this.selectedDevice || newVal.channelNo !== this.selectedChannel) {
          this.selectedDevice = newVal.deviceNo || '';
          this.selectedChannel = newVal.channelNo || '';
          this.updateChannelOptions();
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    // 自动加载数据
    if (this.autoLoad) {
      this.loadDevicesAndChannels();
    }
  },
  methods: {
    // 加载设备和通道数据
    async loadDevicesAndChannels() {
      this.loading = true;
      try {
        const response = await getDevicesAndChannels();
        if (response && response.data) {
          this.allChannelsData = response.data;
          this.processDeviceOptions();
          this.updateChannelOptions();

          // 不再自动选择第一个设备，保持为"请选择"
          // 如果需要自动选择，可以在这里设置
          if (this.autoSelectFirstDevice && this.deviceOptions.length > 0) {
            this.selectedDevice = this.deviceOptions[0].value;
            this.handleDeviceChange(this.selectedDevice, true);
          }

          // 发出加载完成事件
          this.emitLoadComplete();

        } else {
          console.warn('获取设备通道数据为空');
          this.deviceOptions = [];
          this.channelOptions = [];
          // 即使数据为空也发出加载完成事件
          this.emitLoadComplete();
        }
      } catch (error) {
        console.error('加载设备通道数据失败:', error);
        this.$message.error('加载设备通道数据失败');
        this.deviceOptions = [];
        this.channelOptions = [];
        // 即使加载失败也发出加载完成事件
        this.emitLoadComplete();
      } finally {
        this.loading = false;
        this.isFirstLoad = false;
      }
    },

    // 发出加载完成事件
    emitLoadComplete() {
      const selectedChannelDetail = this.channelOptions.find(
        channel => channel.value === this.selectedChannel
      );

      const loadCompleteData = {
        deviceNo: this.selectedDevice,
        channelNo: this.selectedChannel,
        channelDetail: selectedChannelDetail,
        deviceOptions: this.deviceOptions,
        channelOptions: this.channelOptions,
        isFirstLoad: this.isFirstLoad
      };

      console.log('设备通道数据加载完成:', loadCompleteData);
      this.$emit('load-complete', loadCompleteData);
    },

    // 处理设备选项
    processDeviceOptions() {
      if (!this.allChannelsData || this.allChannelsData.length === 0) {
        this.deviceOptions = [];
        return;
      }

      // 去重并格式化设备选项
      const uniqueDevices = [...new Set(this.allChannelsData.map(item => item.deviceNo))];
      this.deviceOptions = uniqueDevices.map(deviceNo => ({
        label: `设备${deviceNo}`,
        value: deviceNo
      }));
    },

    // 更新通道选项
    updateChannelOptions() {
      if (!this.allChannelsData || this.allChannelsData.length === 0) {
        this.channelOptions = [];
        return;
      }

      // 根据选中的设备过滤通道
      if (this.selectedDevice) {
        this.channelOptions = this.allChannelsData
          .filter(item => item.deviceNo === this.selectedDevice)
          .map(channel => ({
            label: `通道${channel.channelNo}`,
            value: channel.channelNo,
            startMeter: Number(channel.startMeter) || 1,
            endMeter: Number(channel.endMeter) || 1500
          }));
      } else {
        this.channelOptions = [];
        this.selectedChannel = '';
      }

      // 不再自动选择第一个通道
      if (this.autoSelectFirstChannel && this.channelOptions.length > 0) {
        this.selectedChannel = this.channelOptions[0].value;
        this.handleChannelChange(this.selectedChannel, true);
      }
    },

    // 设备变更处理
    handleDeviceChange(deviceNo, isAutoSelect = false) {
      // 设备变更时清空通道选择
      this.selectedChannel = '';

      // 更新通道选项
      this.updateChannelOptions();

      // 发出变更事件
      this.emitChange();
    },

    // 通道变更处理
    handleChannelChange(channelNo, isAutoSelect = false) {
      // 发出变更事件
      this.emitChange();
    },

    // 发出变更事件
    emitChange() {
      const selectedChannelDetail = this.channelOptions.find(
        channel => channel.value === this.selectedChannel
      );

      const selection = {
        deviceNo: this.selectedDevice,
        channelNo: this.selectedChannel,
        channelDetail: selectedChannelDetail
      };

      console.log('设备通道选择变更:', selection);

      // 更新内部数据
      this.$emit('input', selection);
      this.$emit('change', selection);
    },

    // 外部调用方法：重新加载数据
    async reload() {
      await this.loadDevicesAndChannels();
    },

    // 外部调用方法：获取当前选择
    getSelection() {
      const selectedChannelDetail = this.channelOptions.find(
        channel => channel.value === this.selectedChannel
      );

      return {
        deviceNo: this.selectedDevice,
        channelNo: this.selectedChannel,
        channelDetail: selectedChannelDetail
      };
    },

    // 外部调用方法：设置选中的设备
    setDevice(deviceNo) {
      this.selectedDevice = deviceNo;
      this.handleDeviceChange(deviceNo);
    },

    // 外部调用方法：设置选中的通道
    setChannel(channelNo) {
      this.selectedChannel = channelNo;
      this.handleChannelChange(channelNo);
    },

    // 外部调用方法：重置选择
    reset() {
      this.selectedDevice = '';
      this.selectedChannel = '';
      this.updateChannelOptions();
      this.emitChange();
    },

    // 外部调用方法：清空选择
    clear() {
      this.selectedDevice = '';
      this.selectedChannel = '';
      this.channelOptions = [];
      this.emitChange();
    }
  }
};
</script>

<style scoped>
.device-channel-selector {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

/* 紧凑模式样式 */
.device-channel-selector.compact {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  margin-right: 12px;
  vertical-align: top;
}

.selector-item {
  margin-bottom: 0 !important;
}

.compact-item {
  margin-bottom: 0 !important;
  margin-right: 0 !important;
}

.device-select,
.channel-select {
  min-width: 150px;
}

.compact-select {
  width: 120px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .device-channel-selector {
    flex-direction: column;
    gap: 12px;
  }

  .device-channel-selector.compact {
    flex-direction: row;
    gap: 8px;
  }

  .device-select,
  .channel-select {
    width: 100%;
  }

  .compact-select {
    width: 120px;
  }
}
</style>
